package com.leave.mos.controller;

import com.leave.mos.entity.User;
import com.leave.mos.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author lh
 * @Date 2021/7/1 17:28
 * @Version 1.0
 **/
@Controller
@RequestMapping("data")
public class LoginController {

    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private LoginService loginService;

    @PostMapping("login")
    public String login(User user, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {

        if(user == null){
            model.addAttribute("msg","请输入账号密码！");
            return "index";
        }
        if(StringUtils.isBlank(user.getUsername())){
            model.addAttribute("msg","请输入账号！");
            return "index";
        }
        if(StringUtils.isBlank(user.getPassword())){
            model.addAttribute("msg","请输入密码！");
            return "index";
        }

        User userDb = loginService.getUserInfoByUsername(user);

        if(userDb == null){
            model.addAttribute("msg","账号密码错误！");
            return "index";
        }

        //放到session中
        HttpSession session = request.getSession(true);
        session.setAttribute("user",userDb);

        logger.info("打印：{}",user.toString());
        model.addAttribute("user",userDb);

        //response.sendRedirect(request.getServletContext().getContextPath()+"index");
        return "upload";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession httpsession = request.getSession(true);
        return "index";
    }
}
